package club.zhangliyuanblog.controller;

import club.zhangliyuanblog.entity.User;
import club.zhangliyuanblog.service.UserService;
import club.zhangliyuanblog.vo.Result;
import com.alibaba.druid.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liyuan.zhang
 * @date 2021/2/18 23:05
 */
@Api("用户管理Api")
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("查询所有用户")
    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }


    @ApiOperation("保存用户信息")
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        Result result = new Result();
        try {
            if (StringUtils.isEmpty(user.getId())) {
                userService.save(user);
                result.setMsg("用户信息保存成功");
            }else {
                userService.update(user);
                result.setMsg("用户信息编辑成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统错误，请稍后再试。。");
            result.setStatus(false);
        }
        return result;
    }

    @ApiOperation("根据用户id删除用户信息")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable(value = "id") Integer id) {
        Result result = new Result();
        try {
            userService.deleteUserById(id);
            result.setMsg("删除成功");
        } catch (Exception e) {
            result.setStatus(false);
            result.setMsg("删除失败");
            e.printStackTrace();
        }
        return result;
    }


    @ApiOperation("分页查找用户api")
    @GetMapping("/findByPage")
    public Map<String, Object> findByPage(Integer pageNow, Integer pageSize) {
        pageNow = pageNow == null ? 1 : pageNow;
        pageSize = pageSize == null ? 5 :pageSize;
        Map<String, Object> result = new HashMap<>();
        List<User> users = userService.findUserByPage(pageNow, pageSize);
        Long totals = userService.findTotals();
        result.put("users",users);
        result.put("total",totals);
        return result;
    }
}
